//项目管理
import * as React from 'react';
import {
  Modal,
  Row,
  Col,
  Input,
  Table,
  Button,
  Form,
  Select,
  Upload,
  Icon,
  message,
  Dropdown,
  Menu,
  Spin,
  Tooltip,
  notification,
  Popover
} from 'antd';

import router from 'umi/router';
import Link from 'umi/link';
import axios from 'axios';
import Api from '../../services/apis';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';


const FormItem = Form.Item;
const Option = Select.Option;
const Dragger = Upload.Dragger;
@connect(({ user, loading }) => ({
  currentUser: user.currentUser,
  currentUserLoading: loading.effects['user/fetchCurrent']
}))

class assetsReceived extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: '',
      tranUnits: '',
      tranType: '',
      canJump: false,
      current: 1,
      totalSize: 0,
      tableData: [],
      modalVisible: false,
      projectCode: '',
      loading: true,
      projectName: "",
      transferUnit: "",
      assetStatus: "",
      showDownload: false,
      downloadLink: '',
      startDownload: false,
      downloadName: '',
      addProjectModalVisible: false,
      ownerStatus: [],
      ownerType: [],
      signStatus: [],
      manageAssetStatus: [],
      province: [],
      city: [],
      district: [],
      fileType: 1
    };
  }

  componentWillMount() {
    const that = this;
    this.getData(1);

    //获取系统参数
    axios.all([this.getSysDic("OWNER_SHIP_STATUS"), this.getSysDic("OWNER_SHIP_TYPE"), this.getSysDic("SIGN_STATUS"), this.getSysDic("ASSET_STATUS")])
      .then(axios.spread(function (r1, r2, r3, r4) {
        that.setState({
          ownerStatus: r1.data, //权证状态
          ownerType: r2.data,  //权证类型
          signStatus: r3.data,  //签署协议状态
          manageAssetStatus: r4.data,  //资产状态
        })
      }))


  }

  ///获取系统参数
  getSysDic = (type) => {
    return axios.post(Api.amGetSysDic, { key: type })
  }

  setAddProjectModalVisible(visible) {
    this.setState({ addProjectModalVisible: visible })
  }

  setModalVisible(modalVisible, state, fileType) {
    this.setState({ modalVisible });
    if (fileType !== undefined) {
      this.setState({
        fileType
      });
    };
    if (state === 'ok' && Number(sessionStorage.getItem('isMap')) === 1) {
      router.push({
        pathname: '/fe/assetManagement/dataCorrection',
        state: {
          projectCode: this.state.projectCode,
          type: 'upload'
        }
      });
    }
  }
  showDownload(showDownload) {
    this.setState({ showDownload });
  }

  getProject(id) {
    console.log(id);
  };

  query() {
    this.getData(1);
  }

  changeName(e) {
    e.persist();
    this.setState({ projectName: e.target.value });
  };

  changeTranUnits(e) {
    e.persist();
    this.setState({ transferUnit: e.target.value });
  };

  changeTranType(e) {
    this.setState({ assetStatus: e });
  };

  //操作--资产接收(跳页版)
  goReceived = () => {
    const page = {
      pathname: '/received',
      query: {},
    };
    history.push(page);
  };

  //操作--资产接收(弹框 版)
  getReceived = () => { };
  handleMenuClick(e) {
    console.log('click', e);
  }

  setModifyVisible = visible => {
    this.setState({ modifyVisible: visible });
  };


  exportExcel() {
    this.setState({
      startDownload: false
    });
    axios.get(Api.exportPro, {
      params: {
        projectName: this.state.projectName,
        transferUnit: this.state.transferUnit,
        assetStatus: this.state.assetStatus
      },
      responseType: 'arraybuffer'
    }).then((res) => {
      message.success('开始下载！');

      let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
      const [dLink, name] = [
        window.URL.createObjectURL(blob),
        `资产接收列表${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}.xls`
      ];
      let link = document.createElement('a');
      link.href = dLink;
      link.download = name;
      link.click();
      this.setState({
        startDownload: true,
        downloadLink: dLink,
        downloadName: name,
        showDownload: true
      });
    }).catch((err) => {
      message.error(`下载失败！错误信息：${err}`);
    });
  }

  getData(page) {
    this.setState({ loading: true })
    axios.get(Api.queryProject, {
      params: {
        offset: page,
        projectName: this.state.projectName,
        transferUnit: this.state.transferUnit,
        assetStatus: this.state.assetStatus
      }
    }).then((res) => {
      const tableData = res.data.list;
      for (let i = 0, len = tableData.length; i < len; i++) {
        tableData[i].key = i;
      };


      this.setState({
        tableData,
        count: res.data.count
      });
      this.toggleLoading(false);
    }).catch((err) => {
      this.toggleLoading(false);
    });
  }

  toggleLoading(loading) {
    this.setState({
      loading
    });
  }

  changePage(page) {
    this.setState({
      current: page
    });
    this.getData(page);
  }

  addProject = () => {
    const that = this;
    this.setState({ loading: true })
    that.props.form.validateFields((err, values) => {
      if (!err) {
        axios.post(Api.amAddProjectInfo, {
          projectCode: values.code,
          projectName: values.name,
          transferUnit: values.transferUnits,
          manageType: values.manageType,
          obtainWay: values.obtainWay,
        })
          .then(function (resp) {
            const { data } = resp;
            if (data.code == 0) {
              notification.destroy();
              notification['error']({ message: data.msg });
            } else if (data.code == 1) {
              notification.destroy();
              notification['success']({ message: data.msg });
              that.setAddProjectModalVisible(false);
              that.getData(1);
            } else if (data.code == 2) {
              notification.destroy();
              notification['warning']({ message: data.msg });
            }

            that.setState({ loading: true })
          })
      }
    })
  }

  render() {
    let that = this;
    const { form: { getFieldDecorator }, currentUserLoading } = this.props;

    //表格表头
    const columns = [
      {
        title: '项目名称',
        dataIndex: 'projectName',
        key: 'projectName',
      },
      {
        title: '项目编号',
        dataIndex: 'projectCode',
        key: 'projectCode',
      },
      {
        title: '划转单位',
        dataIndex: 'transferUnit',
        key: 'transferUnit',
      },
      {
        title: '房屋核实',
        dataIndex: 'verifyDate',
        key: 'verifyDate',
      },
      {
        title: '上报核实报告',
        dataIndex: 'upVerifyDate',
        key: 'upVerifyDate',
      },
      {
        title: '上报划转请示',
        dataIndex: 'upTransferDate',
        key: 'upTransferDate',
      },
      {
        title: '划转批复',
        dataIndex: 'transferDate',
        key: 'transferDate',
      },
      {
        title: '协议签署',
        dataIndex: 'signStatus',
        key: 'signStatus',
      },
      {
        title: '资产状态',
        dataIndex: 'assetStatus',
        key: 'assetStatus',
      },
      {
        title: '省',
        dataIndex: 'province',
        key: 'province',
      },
      {
        title: '市',
        dataIndex: 'city',
        key: 'city',
      },
      {
        title: '区',
        dataIndex: 'area',
        key: 'area',
      },
      {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        render: (text, item, index) => (
          <div key={index}>
            <Dropdown.Button onClick={this.getProject.bind(this, item.userId)} overlay={
              <Menu onClick={this.handleMenuClick.bind(this)}>
                <Menu.Item key="details">
                  <Link
                    key={index}
                    to={{
                      pathname: '/fe/assetManagement/assetReceiptDetails',
                      state: {
                        projectCode: item.projectCode,
                        canEdit: true
                      }
                    }}>
                    编辑
                </Link>
                </Menu.Item>
              </Menu>
            }>
              <Link
                key={index}
                to={{
                  pathname: '/fe/assetManagement/assetReceiptDetails',
                  state: {
                    projectCode: item.projectCode,
                    canEdit: false
                  }
                }}>详情</Link>
            </Dropdown.Button>
          </div>
        ),
      },
    ];

    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      }
    };


    return (

      <PageHeaderWrapper
        loading={currentUserLoading}
      >
        <div className="mainContainer">
          <div className='contentHeader'>
            <div className="contentHeaderTitle">
              <p>资产接收</p>
              <p>ASSETS RECEIVED</p>
            </div>
          </div>
          <Form layout="inline">
            <FormItem label='项目名称：'>
              <Input
                value={this.state.projectName}
                data-inp="zdbh"
                onChange={this.changeName.bind(this)}
                placeholder="请输入项目名称"
              />
            </FormItem>
            <FormItem label='划转单位：'>
              <Input
                value={this.state.transferUnit}
                data-inp="zdbh"
                onChange={this.changeTranUnits.bind(this)}
                placeholder="请输入划转单位"
              />
            </FormItem>
            <FormItem label='资产状态：'>
              <Select
                showSearch
                placeholder="请选择项目名称"
                optionFilterProp="children"
                onChange={this.changeTranType.bind(this)}
                filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
              >
                <Option value="5">接管中</Option>
                <Option value="7">待接管</Option>
                <Option value="8">已接管</Option>
                <Option value="9">运营中</Option>
              </Select>
            </FormItem>
            <Row>
              <Col span={24} style={{ textAlign: 'center', marginBottom: '10px' }}>
                <Button icon="search" type="primary" className="evfilterbtn" onClick={this.query.bind(this)}>
                  查询
                  </Button>
                &emsp;
                <Popover placement="top" title='请选择上传类型' content={
                  <div>
                    <Button type="primary" onClick={this.setModalVisible.bind(this, true, 'Placeholder', 1)}>资产接收</Button>
                    &emsp;
                    <Button type="primary" onClick={this.setModalVisible.bind(this, true, 'Placeholder', 2)}>二次接收</Button>
                  </div>
                } trigger="click">
                  <Button icon="cloud-upload"
                    type="primary"
                    className="evfilterbtn"
                  >
                    上传
                  </Button>
                </Popover>
                &emsp;
                  <Button icon="plus-circle"
                  onClick={() => this.setAddProjectModalVisible(true)}
                  type="primary"
                  htmlType="reset"
                  className="evfilterbtn"
                >
                  新建项目
                </Button>
                &emsp;
                  <Button icon='profile' ghost
                  onClick={this.exportExcel.bind(this)}
                  type="primary"
                  htmlType="reset"
                  className="evfilterbtn"
                >
                  生成报表
                </Button>
              </Col>
            </Row>
          </Form>
          <Spin spinning={this.state.loading}>
            <Row>
              <Table
                bordered={true}
                scroll={{ x: true }}
                align={'center'}
                columns={columns}
                dataSource={this.state.tableData}
                pagination={{
                  current: that.state.current,
                  total: that.state.totalSize,
                  onChange: this.changePage.bind(this),
                  showTotal: total => `共 ${total} 项`
                }}
              />
            </Row>

            <Modal
              zIndex='9999'
              title="上传"
              visible={this.state.modalVisible}
              width={830}
              wrapClassName="vertical-center-modal"
              onOk={this.setModalVisible.bind(this, false, 'ok')}
              onCancel={this.setModalVisible.bind(this, false, 'cancel')}
              okButtonProps={{
                disabled: !this.state.canJump
              }}
            >
              <Dragger
                name='file'
                multiple={false}
                action={Api.upload}
                data={{
                  flag: this.state.fileType
                }}
                accept='.xls,.xlsx'
                onChange={(info, list) => {
                  const len = info.fileList.length;
                  if (len === 0) {
                    this.setState({
                      canJump: false
                    });
                  };
                  if (len > 1) {
                    info.fileList.splice(0, len - 1);
                  };
                  let projectCode = '';
                  if (info.file.response) {
                    projectCode = info.file.response
                  };

                  this.setState({
                    projectCode
                  });

                  const status = info.file.status;
                  if (status === 'done') {
                    message.success(`${info.file.name} 上传成功。`);
                    if (!this.state.canJump) {
                      this.setState({
                        canJump: true
                      });
                    };
                  } else if (status === 'error') {
                    message.error(`${info.file.name} 上传失败。`);
                  }
                }}
              >
                <p className="ant-upload-drag-icon">
                  <Icon type="inbox" />
                </p>
                <p className="ant-upload-text">点击或将文件拖拽到这里上传</p>
                <p className="ant-upload-hint">支持扩展名：.xls .xlsx</p>
              </Dragger>
            </Modal>

            <Modal
              zIndex='9999'
              title="开始下载"
              visible={this.state.showDownload}
              width={400}
              wrapClassName="vertical-center-modal"
              onOk={this.showDownload.bind(this, false, 'ok')}
              onCancel={this.showDownload.bind(this, false, 'cancel')}
              style={{
                textAlign: 'center'
              }}
            >
              {this.state.downloadName !== '' ?
                <div>
                  <p>开始自动下载...</p>
                  <p><a download={this.state.downloadName} href={this.state.downloadLink}>下载没有开始，点击此链接手动下载。</a></p>
                </div>
                :
                <div>
                  <p>文件生成中，请稍后。</p>
                  <p><Icon type="loading" /></p>
                </div>
              }
            </Modal>

            {/* 新建项目弹框 */}
            <Modal
              title="新建项目"
              visible={this.state.addProjectModalVisible}
              width={830}
              onOk={this.addProject}
              onCancel={() => this.setAddProjectModalVisible(false)}
            >
              <Row gutter={24}>
                <Col span={8}>
                  <FormItem label="项目名称：">
                    {getFieldDecorator('name', {
                      rules: [{ required: true, message: '请输入项目名称！' }]
                    })(<Input placeholder="请输入项目名称" />)}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label="项目编号：">
                    {getFieldDecorator('code', {
                      rules: [{ required: true, message: '请输入项目编号！' }]
                    })(<Input placeholder="请输入项目编号" />)}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label="划转单位：">
                    {getFieldDecorator('transferUnits', {
                      rules: [{ required: true, message: '请输入划转单位！' }]
                    })(<Input placeholder="请输入划转单位" />)}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label="管理方式：">
                    {getFieldDecorator('manageType', {
                      rules: [{ required: true, message: '请输入管理方式！' }]
                    })(<Select style={{ width: '100%' }}
                      placeholder="请选择管理方式"
                    >
                      <Option value='自管'>自管</Option>
                      <Option value='托管'>托管</Option>
                    </Select>)}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label="取得方式：">
                    {getFieldDecorator('obtainWay', {
                      rules: [{ required: true, message: '请输入取得方式！' }]
                    })(<Select placeholder="请选择取得方式" style={{ width: '100%' }}
                    >
                      <Option value='划转'>划转</Option>
                      <Option value='收购'>收购</Option>
                    </Select>)}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label="土地面积：">
                    {getFieldDecorator('landArea', {
                      rules: [{ required: true, message: '请输入土地面积！' }, { pattern: /^[0-9]+([.]{1}[0-9]+){0,1}$/, message: '请输入数值！' }]
                    })(<Input placeholder="请输入土地面积" />)}
                  </FormItem>
                </Col>
              </Row>
            </Modal>
          </Spin>
        </div>
      </PageHeaderWrapper >
    );
  }
}

const WrappedApp = Form.create()(assetsReceived);
export default WrappedApp;